import json,re,random,io,sys,requests,time
# import jieba,jieba.posseg as pseg

from django.shortcuts import render
from django.views import View
from django.http import JsonResponse,QueryDict,HttpResponse
from django.views.decorators.csrf import csrf_exempt

from py2neo import Graph,Node,Relationship
# Create py2neo connection
graph = Graph(host='localhost',auth=('neo4j','123'))
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
# jieba.load_userdict(r"E:\py-work\jdangoprojectjd\mydict.txt")

# Create your views here.
@csrf_exempt
def initServices(request):
    global graph
    name = eval(request.body.decode()).get('name')
    url = eval(request.body.decode()).get('serviceHost')
    index = url.find('/rest/services')
    if index == -1:
        return JsonResponse({"status":"error","success":False})
    else:
        rootUrl = url[0:index]+"/rest/services"

        server = graph.nodes.match("My_ArcGisServer", url=rootUrl).first()
        if not server:
            return JsonResponse({"status": "ok","success": True,"url":url,"data":server})
        # services = _getServiceUrls(rootUrl)

        # 创建一个根站点实体
        # a = Node("My_ArcGisServer", url=rootUrl, name= name, date=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        # graph.create(a)
        #
        # for service in services:
        #     serverUrl = rootUrl + "/" + service["name"] + "/" + service["type"]
        #     if service["type"] == "MapServer":
        #         layers = _getLayers(serverUrl)
        #     elif service["type"] == "ImageServer":
        #         layers = []
        #
        #     _createNodeAndRelationship(a,service,serverUrl,layers)

        sql = "MATCH (n:My_ArcGisServer{url:'" + url + "'}) -[:HAS]->(m)-[:HAS]->(l) return n,m,l"
        nodes_source = graph.run(sql).data()

        return JsonResponse({"status": "ok","success": True,"url":url,"name":name, "data":nodes_source})


def _createNodeAndRelationship(root,service,url,layers):
    s = Node("My_Service", name=service["name"],url=url, type=service["type"])
    rs = Relationship(root, "HAS", s)
    graph.create(s)
    graph.create(rs)

    #[{"id":0,"name":"Dark Gray Canvas Base","parentLayerId":-1,"defaultVisibility":true,"subLayerIds":null,"minScale":0,"maxScale":0}]
    for layer in layers:
        l = Node("My_Layer", id = layer["id"], name=layer["name"], defaultVisibility=layer["defaultVisibility"],minScale=layer["minScale"],maxScale=layer["maxScale"])
        graph.create(l)
        sl = Relationship(s, "HAS", l)
        graph.create(sl)

# http://server.arcgisonline.com/arcgis/rest/services
def _getServiceUrls(url):
    # 爬取的网页链接
    services = []
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            r = requests.get(url+ "?f=pjson",timeout = 200)
            break
        except requests.exceptions.ConnectionError:
            print('ConnectionError -- please wait 3 seconds')
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print('ChunkedEncodingError -- please wait 3 seconds')
            time.sleep(3)
        except:
            print('Unfortunitely -- An Unknow Error Happened, Please wait 3 seconds')
            time.sleep(3)

    print(r.text)
    result = json.loads(r.text)
    if len(result["folders"]):
        for node in result["folders"]:
            print(url+"/"+node)
            newServices = _getServiceUrls(url+"/"+node)
            services += newServices

    services += result["services"]
    return services

def _getLayers(url):
    print(url)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            r = requests.get(url+ "?f=pjson",timeout = 200)
            break
        except requests.exceptions.ConnectionError:
            print('ConnectionError -- please wait 3 seconds')
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print('ChunkedEncodingError -- please wait 3 seconds')
            time.sleep(3)
        except:
            print('Unfortunitely -- An Unknow Error Happened, Please wait 3 seconds')
            time.sleep(3)

    result = json.loads(r.text)
    print(result["layers"])
    return result["layers"]

@csrf_exempt
def likeService(request):
    global graph
    userId = eval(request.body.decode()).get('userId')
    serviceId = eval(request.body.decode()).get('serviceId')
    try:
        user = graph.nodes.match("My_User", id=userId).first()
        service = graph.nodes.match("My_Service", id=serviceId).first()
        rel_a = Relationship(user, "likes", service)
        graph.create(rel_a)
        return JsonResponse({"status": "ok","success":True})
    except:
        return JsonResponse({"status": "error","success": False})

@csrf_exempt
def getServerHostAndServiceAndLayerByUrl(request):
    global graph
    url = eval(request.body.decode()).get('serviceHost')
    sql = "MATCH (n:My_ArcGisServer{url:'"+url+"'}) -[:HAS]->(m)-[:HAS]->(l) return n,m,l"
    nodes_source = graph.run(sql).data()

    return JsonResponse({"status": "ok","success":True,"data":nodes_source})

@csrf_exempt
def fetchJieba(request):
    global graph
    words = eval(request.body.decode()).get('words')
    result = []
    chixings = []
    words = pseg.cut(words);
    for i in words:
        result.append(i.word)
        chixings.append(i.flag)
    print(result)
    return JsonResponse({"status": "ok", "success": True, "data": {"words":result,"chixing":chixings}})


@csrf_exempt
def fetchSearch(request):
    global graph
    input1 = eval(request.body.decode()).get('input1')
    input2 = eval(request.body.decode()).get('input2')
    selectValue = eval(request.body.decode()).get('selectValue')
    print(input1,input2,selectValue)

    if selectValue == "service-layer":
        sql = "match(n:SERVICE)-[:INCLUDE]->(m:LAYER) where n.name =~'.*"+input1+".*' and m.name =~'.*"+input2+".*' return n,m"
        nodes_source = graph.run(sql).data()
    if selectValue == "user-service":
        sql = "match(n:My_User)-[:My_Like]->(m:SERVICE) where n.name =~'.*" + input1 + ".*' and m.name =~'.*" + input2 + ".*' return n,m"
        nodes_source = graph.run(sql).data()
    if selectValue == "station-service":
        sql = "match(n:My_ArcGisServer)-[:INCLUDE]->(m:SERVICE) where n.name =~'.*"+input1+".*' and m.name =~'.*"+input2+".*' return n,m"
        nodes_source = graph.run(sql).data()

    return JsonResponse({"status": "ok","success":True,"data":nodes_source})

myDicts = ["地图服务",
      "中国境界线",
      "中国城市",
      "中国省会城市",
      "中国主要公路",
      "中国主要铁路",
      "中国地级市",
      "中国县级城市",
      "中国主要湖泊",
      "中国主要河流",
      "中国一级面状河流",
      "北京市省道",
      "北京市市区道路",
      "北京市地铁",
      "北京市人行道",
      "北京市高速公路",
      "北京市铁路",
      "北京市国道",
      "北京市交通站点",
      "北京市酒店",
      "北京市湖泊",
      "北京市绿地",
      "北京市景点",
      "北京市公共厕所",
      "北京市收费站",
      "北京市公园",
      "北京市河流",
      "北京市港口",
      "北京市乡镇",
      "北京市医疗机构",
      "北京市村庄"]

@csrf_exempt
def fetchJiebaSearch(request):
    global graph
    words = eval(request.body.decode()).get('words')
    result = []
    words2 = pseg.cut(words)
    conditions = ''
    for i in words2:
        result.append(i.word)
        if i.word in myDicts:
            conditions += "n.name =~'.*"+i.word+".*' or "
    print(result)
    print(conditions[:-3])
    sql = "match(n:SERVICE) where "+conditions[:-3]+" return n"
    nodes_source = graph.run(sql).data()
    return JsonResponse({"status": "ok","success":True,"data":nodes_source})


@csrf_exempt
def fetchLayer(request):
    global graph
    name = eval(request.body.decode()).get('name')
    sql = "match(n:SERVICE)-[:INCLUDE]->(m:LAYER) where n.name = '"+name+"' return n,m"
    nodes_source = graph.run(sql).data()
    return JsonResponse({"status": "ok","success":True,"data":nodes_source})

@csrf_exempt
def goLike(request):
    global graph
    u_name = eval(request.body.decode()).get('u_name')
    s_name = eval(request.body.decode()).get('s_name')
    r_value = eval(request.body.decode()).get('r_value')
    sql = "match(u:My_User{name:'"+u_name+"'})-[r:My_Like]->(s:SERVICE{name:'"+s_name+"'}) return r"
    nodes_source1 = graph.run(sql).data()
    if len(nodes_source1):
        print(nodes_source1)
        sql = "match(u:My_User{name:'"+u_name+"'})-[r:My_Like]->(s:SERVICE{name:'"+s_name+"'}) SET r={rate:"+str(r_value)+"} return r"
        nodes_source3 = graph.run(sql).data()
        return JsonResponse({"status": "ok", "success": True, "data": nodes_source3})
    else:
        sql = "match(u:My_User{name:'"+u_name+"'}),(s:SERVICE{name:'"+s_name+"'}) create (u)-[:My_Like{rate:"+str(r_value)+"}]->(s)"
        nodes_source2 = graph.run(sql).data()
        return JsonResponse({"status": "ok", "success": True, "data": nodes_source2})



@csrf_exempt
def tuiJian(request):
    global graph
    u_name = eval(request.body.decode()).get('u_name')
    sql1 = "match(u:My_User)-[r:My_Like]->(s:SERVICE) WITH s, sum(r.rate) AS sum order by sum desc return s,sum"
    nodes_source1 = graph.run(sql1).data()
    sql2 = "match(u:My_User{name:'"+u_name+"'})-[r:My_Like]->(s:SERVICE) return s"
    nodes_source2 = graph.run(sql2).data()
    return JsonResponse({"status": "ok", "success": True, "data": {'allRate':nodes_source1,'uLike':nodes_source2}})

